package com.xuxin.baby.activity;

import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.haibin.calendarview.Calendar;
import com.haibin.calendarview.CalendarView;
import com.xuxin.baby.R;
import com.xuxin.baby.base.BaseActivity;
import com.xuxin.baby.base.BaseConstant;
import com.xuxin.baby.bean.SignBean;
import com.xuxin.baby.bean.BaseBean;
import com.xuxin.baby.contract.UserSignContract;
import com.xuxin.baby.presenter.UserSignPresenter;
import com.xuxin.baby.utils.ACache;
import com.xuxin.baby.utils.BaseUtils;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by xu_xin
 * Created on 2020.08.07 0007
 * 签到
 */
public class UserSignActivity extends BaseActivity implements UserSignContract.View {
    private final UserSignContract.Presenter presenter = new UserSignPresenter(this);
    @BindView(R.id.view_title)
    LinearLayout view_title;
    @BindView(R.id.view_line)
    ImageView view_line;
    @BindView(R.id.title_left)
    ImageView title_left;
    @BindView(R.id.title_right)
    ImageView title_right;
    @BindView(R.id.title_name)
    TextView title_name;
    @BindView(R.id.sign_num)
    TextView sign_num;
    @BindView(R.id.sign_time)
    TextView sign_time;
    @BindView(R.id.sign_calendar)
    CalendarView sign_calendar;

    private String memberId;//用户ID
    private String tenantId;//租户id
    private String token;//授权token


    @Override
    public void setContentView() {
        setContentView(R.layout.activity_user_sign);
    }

    @Override
    public void initView() {
        title_name.setText("");
        view_title.setBackgroundResource(R.color.transparent);
        view_line.setBackgroundResource(R.color.transparent);
        title_left.setImageResource(R.mipmap.img_left_white);
        String date = sign_calendar.getCurYear() + "年" + sign_calendar.getCurMonth() + "月";
        sign_time.setText(date);
    }

    @Override
    public void initData() {
        ACache aCache = ACache.get(this);
        memberId = aCache.getAsString(BaseConstant.memberId);
        tenantId = aCache.getAsString(BaseConstant.tenantId);
        token = aCache.getAsString(BaseConstant.token);
        handler.sendEmptyMessage(0);
    }

    @Override
    public void onComplete() {

    }

    @Override
    @OnClick({R.id.title_left, R.id.user_sign_update})
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.title_left) {
            finish();
        } else if (id == R.id.user_sign_update) {
            handler.sendEmptyMessage(1);
        }
    }

    private final Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case 0:
                    presenter.getUserSign(tenantId, token, memberId, 0);
                    break;
                case 1:
                    SimpleDateFormat format = TimeUtils.getSafeDateFormat("yyyy-MM-dd");
                    presenter.sign(tenantId, token, memberId, TimeUtils.getNowString(format));
                    break;
            }
            return false;
        }
    });

    @Override
    public void onSuccess(SignBean signBean) {
        if (null != signBean && null != signBean.getResult()) {
            setDate(signBean);
        }
    }

    @Override
    public void onSuccess(BaseBean baseBean) {
        ToastUtils.showShort("签到成功");
        initData();
    }

    private void setDate(SignBean signBean) {
        List<SignBean.ResultBean.ItemsBean> list = getSignData(signBean);
        if (null != list && list.size() > 0) {
            Map<String, Calendar> map = new HashMap<>();
            for (int i = 0; i < list.size(); i++) {
                try {
                    String time = BaseUtils.getTime(list.get(i).getSignDate());
                    SimpleDateFormat format = TimeUtils.getSafeDateFormat("yyyy-MM-dd");
                    int year = TimeUtils.getValueByCalendarField(time, format, java.util.Calendar.YEAR);
                    int month = TimeUtils.getValueByCalendarField(time, format, java.util.Calendar.MONTH) + 1;
                    int day = TimeUtils.getValueByCalendarField(time, format, java.util.Calendar.DAY_OF_MONTH);
                    map.put(getSchemeCalendar(year, month, day).toString(),
                            getSchemeCalendar(year, month, day));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            sign_calendar.setSchemeDate(map);
        }
    }

    private Calendar getSchemeCalendar(int year, int month, int day) {
        Calendar calendar = new Calendar();
        calendar.setYear(year);
        calendar.setMonth(month);
        calendar.setDay(day);
        calendar.addScheme(new Calendar.Scheme());
        return calendar;
    }

    /**
     * 获取连续签到
     */
    private List<SignBean.ResultBean.ItemsBean> getSignData(SignBean signBean) {
        try {
            if (null != signBean && null != signBean.getResult()
                    && null != signBean.getResult().getItems()
                    && signBean.getResult().getItems().size() > 0) {
                int signNum = signBean.getResult().getItems().get(0).getSignDays();
                if (signNum > 0) {
                    sign_num.setText("已连续签到" + signNum + "天");
                    return signBean.getResult().getItems().subList(0, signNum);
                } else {
                    return null;
                }
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}